package cn.com.lyj6851.auth.authentication;


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.com.lyj6851.common.properties.LoginResponseType;
import cn.com.lyj6851.common.properties.RootSecurityProperties;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 登录成功处理器
 * 功能:通过请求参数: 
 *     构建出:OAuth2Request  Authentication
 * 用户登录成功后,生成一个token返回给调用方;
 * 调用方携带token来访问资源服务器保护的资源    
 */
@Slf4j
@Component
public class YongAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	
	@Autowired
    private RootSecurityProperties securityProperties;
	
	private RequestCache requestCache = new HttpSessionRequestCache();
	@Autowired
    private ObjectMapper objectMapper;
	
	//登录成功执行
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws ServletException, IOException {
		log.info("登录成功!");
	
		if (LoginResponseType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        } else {
        	/**
        	 * 如果设置了micro.service.browser.singInSuccessUrl，总是跳到设置的地址上
        	 * 如果没设置，则尝试跳转到登录之前访问的地址上，如果登录前访问地址为空，则跳到网站根路径上
        	 */
        	if (StringUtils.isNotBlank(securityProperties.getBrowser().getSingInSuccessUrl())) {
                requestCache.removeRequest(request, response);
                setAlwaysUseDefaultTargetUrl(true);
                setDefaultTargetUrl(securityProperties.getBrowser().getSingInSuccessUrl());
            }
        	super.onAuthenticationSuccess(request, response, authentication);
        }	    
    }
}
